package com.hand.wfive.adapter;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import androidx.viewpager2.widget.ViewPager2;

import com.hand.wfive.base.BaseFragment;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.util.ArrayList;

public class FragmentAdapter2 extends FragmentStateAdapter {

    private final ArrayList<BaseFragment> fragments;
    private ArrayList<String> titles;

    public FragmentAdapter2(
            @NonNull FragmentActivity fragmentActivity,
            @NonNull ArrayList<BaseFragment> fragments) {
        super(fragmentActivity);
        this.fragments = fragments;
    }

    public FragmentAdapter2(
            @NonNull FragmentActivity fragmentActivity,
            @NonNull ArrayList<BaseFragment> fragments,
            ArrayList<String> titles) {
        super(fragmentActivity);
        this.fragments = fragments;
        this.titles = titles;
    }

    public FragmentAdapter2(
            @NonNull Fragment fragment,
            @NonNull ArrayList<BaseFragment> fragments) {
        super(fragment);
        this.fragments = fragments;
    }

    public FragmentAdapter2(
            @NonNull Fragment fragment,
            @NonNull ArrayList<BaseFragment> fragments,
            ArrayList<String> titles) {
        super(fragment);
        this.fragments = fragments;
        this.titles = titles;
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        return fragments.get(position);
    }

    @Override
    public int getItemCount() {
        return fragments.size();
    }

    public void setupWithViewPager(TabLayout tabLayout, ViewPager2 viewPager2) {
        new TabLayoutMediator(tabLayout, viewPager2, true, (tab, position) -> {
            if (titles != null && titles.size() == fragments.size()) {
                tab.setText(titles.get(position));
            }
        }).attach();
    }
}
